(function(){
	const input = document.getElementById('input');
	const startBtn = document.getElementById('start');
	const resultUrl = document.getElementById('result-url');

	let timerId = undefined;
	let isFetchingProgress = false;
	let isDowloading = false;
	
	input.addEventListener('input', e => {
		startBtn.disabled = input.value === "";
	});

	startBtn.addEventListener('click', e=> {
		const value = input.value;
		if (value === '')
			return;
		input.disabled = true;
		startBtn.disabled = true;
		resultUrl.style.display = "block";
		resultUrl.innerHTML = "启动下载中...";
		setInterval(receiveProgress, 2000);
		fetch('/start', {
			method: 'POST',
			body: JSON.stringify({url: value}),
			headers: {
				'Content-Type': 'application/json'
			}
		}).then(res => res.json())
			.then(response => {
				isDowloading = true;
				receiveProgress();
			}).catch(error => {
				onError();
			});
	});

	function receiveProgress(){
		if (!isDowloading || isFetchingProgress)
			return;
		isFetchingProgress = true;
		resultUrl.innerHTML = "下载进行中...(60%)";
	}

	function onError(){
		if(timerId){
			clearInterval(receiveProgress);
		}
		resultUrl.innerHTML = "<p class='error'>下载失败</p>"
	}
})();
